import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import {
  EnvelopeIcon,
  LockClosedIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ArrowLeftIcon
} from '@heroicons/react/24/outline'
import { Card, Button, Input } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'
import { authService } from '@/services/api/authService'

const forgotPasswordSchema = z.object({
  email: z.string().email('Please enter a valid email address')
})

type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>

export const ForgotPasswordPage: React.FC = () => {
  const [isLoading, setIsLoading] = useState(false)
  const [isSuccess, setIsSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [submittedEmail, setSubmittedEmail] = useState<string>('')

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<ForgotPasswordFormData>({
    resolver: zodResolver(forgotPasswordSchema)
  })

  const onSubmit = async (data: ForgotPasswordFormData) => {
    setIsLoading(true)
    setError(null)

    try {
      await authService.forgotPassword(data.email)
      setSubmittedEmail(data.email)
      setIsSuccess(true)
    } catch (error: any) {
      setError(error.response?.data?.error?.message || 'Failed to send reset email. Please try again.')
    } finally {
      setIsLoading(false)
    }
  }

  const handleResendEmail = async () => {
    if (submittedEmail) {
      setIsLoading(true)
      setError(null)

      try {
        await authService.forgotPassword(submittedEmail)
        setError(null)
      } catch (error: any) {
        setError('Failed to resend email. Please try again.')
      } finally {
        setIsLoading(false)
      }
    }
  }

  if (isSuccess) {
    return (
      <ErrorBoundary>
        <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
          <div className="max-w-md w-full">
            <Card className="p-8 text-center">
              <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
                <CheckCircleIcon className="h-8 w-8 text-green-600" />
              </div>

              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Check your email
              </h2>

              <p className="text-gray-600 mb-6">
                We've sent password reset instructions to{' '}
                <span className="font-medium text-gray-900">{submittedEmail}</span>
              </p>

              <div className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-md p-4">
                  <div className="flex items-start">
                    <EnvelopeIcon className="h-5 w-5 text-blue-400 mt-0.5 mr-3 flex-shrink-0" />
                    <div className="text-sm text-blue-700">
                      <p className="font-medium mb-1">Next steps:</p>
                      <ol className="list-decimal list-inside space-y-1 text-left">
                        <li>Check your email inbox</li>
                        <li>Click the reset link</li>
                        <li>Create a new password</li>
                      </ol>
                    </div>
                  </div>
                </div>

                {error && (
                  <div className="bg-red-50 border border-red-200 rounded-md p-4">
                    <div className="flex items-center">
                      <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
                      <p className="text-sm text-red-700">{error}</p>
                    </div>
                  </div>
                )}

                <div className="space-y-3">
                  <Button
                    onClick={handleResendEmail}
                    loading={isLoading}
                    disabled={isLoading}
                    variant="outline"
                    fullWidth
                  >
                    Resend email
                  </Button>

                  <Button
                    as={Link}
                    to="/auth/login"
                    variant="primary"
                    fullWidth
                    icon={<ArrowLeftIcon />}
                  >
                    Back to Sign In
                  </Button>
                </div>

                <div className="text-sm text-gray-500">
                  <p>Didn't receive the email? Check your spam folder</p>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </ErrorBoundary>
    )
  }

  return (
    <ErrorBoundary>
      <div className="min-h-screen flex">
        {/* Left Side - Branding */}
        <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-blue-600 to-purple-700 relative overflow-hidden">
          <div className="absolute inset-0 bg-black opacity-20"></div>
          <div className="relative z-10 flex flex-col justify-center px-12 text-white">
            <div className="mb-8">
              <div className="flex items-center space-x-3 mb-6">
                <div className="p-3 bg-white bg-opacity-20 rounded-lg">
                  <LockClosedIcon className="h-8 w-8" />
                </div>
                <h1 className="text-3xl font-bold">Reset Password</h1>
              </div>
              <h2 className="text-4xl font-bold mb-4">
                Forgot your password?
              </h2>
              <p className="text-xl text-blue-100 leading-relaxed">
                No worries! Enter your email address and we'll send you a link to reset your password.
              </p>
            </div>

            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-blue-300" />
                <span className="text-blue-100">Secure password reset</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-blue-300" />
                <span className="text-blue-100">Email verification required</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-blue-300" />
                <span className="text-blue-100">Quick and easy process</span>
              </div>
            </div>
          </div>
        </div>

        {/* Right Side - Reset Form */}
        <div className="flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 bg-gray-50">
          <div className="max-w-md w-full">
            <Card className="p-8">
              <div className="text-center mb-8">
                <div className="mx-auto w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mb-4">
                  <LockClosedIcon className="h-8 w-8 text-blue-600" />
                </div>
                <h2 className="text-2xl font-bold text-gray-900">Reset your password</h2>
                <p className="mt-2 text-sm text-gray-600">
                  Remember your password?{' '}
                  <Link
                    to="/auth/login"
                    className="font-medium text-primary-600 hover:text-primary-500"
                  >
                    Sign in here
                  </Link>
                </p>
              </div>

              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                {error && (
                  <div className="flex items-center p-4 bg-red-50 border border-red-200 rounded-md">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
                    <div className="text-sm text-red-700">{error}</div>
                  </div>
                )}

                <div>
                  <Input
                    label="Email address"
                    type="email"
                    placeholder="Enter your email address"
                    leftIcon={<EnvelopeIcon />}
                    error={errors.email?.message}
                    helperText="We'll send password reset instructions to this email"
                    {...register('email')}
                    fullWidth
                  />
                </div>

                <Button
                  type="submit"
                  loading={isLoading}
                  disabled={isLoading}
                  fullWidth
                  size="lg"
                >
                  Send Reset Instructions
                </Button>

                <div className="text-center">
                  <Link
                    to="/auth/login"
                    className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900"
                  >
                    <ArrowLeftIcon className="h-4 w-4 mr-2" />
                    Back to Sign In
                  </Link>
                </div>
              </form>
            </Card>

            <div className="mt-8 text-center">
              <p className="text-xs text-gray-500">
                Need help?{' '}
                <Link to="/support" className="text-primary-600 hover:text-primary-500">
                  Contact Support
                </Link>
              </p>
            </div>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  )
}
